<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>语音转文字示例</title>
</head>

<body>

  <h1>语音转文字示例</h1>
  <button id="start-btn">开始语音识别</button>
  <button id="stop-btn" disabled>停止语音识别</button>
  <p id="transcript">识别结果将在这里显示...</p>

  <script>
    // 检查浏览器是否支持Web Speech API
    var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;

    if (typeof SpeechRecognition !== 'undefined') {
      // 创建一个SpeechRecognition对象
      var recognition = new SpeechRecognition();

      // 设置属性
      recognition.continuous = true; // 是否持续监听
      recognition.interimResults = true; // 是否返回临时结果
      recognition.lang = 'zh-CN'; // 设置语言为中文

      // DOM元素
      var startBtn = document.getElementById('start-btn');
      var stopBtn = document.getElementById('stop-btn');
      var transcriptParagraph = document.getElementById('transcript');

      // 开始语音识别
      startBtn.onclick = function () {
        recognition.start();
        startBtn.disabled = true;
        stopBtn.disabled = false;
        transcriptParagraph.textContent = '识别中...';
      };

      // 停止语音识别
      stopBtn.onclick = function () {
        recognition.stop();
        startBtn.disabled = false;
        stopBtn.disabled = true;
      };

      // 当识别到语音时触发
      recognition.onresult = function (event) {
        var final_transcript = '';
        var interim_transcript = '';

        // 遍历结果
        for (var i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results[i].isFinal) {
            final_transcript += event.results[i][0].transcript;
          } else {
            interim_transcript += event.results[i][0].transcript;
          }
        }

        // 更新页面上的显示
        transcriptParagraph.innerHTML = '最终结果：' + final_transcript + '<br>' + '临时结果：' + interim_transcript;
      };

      // 当语音识别服务结束时触发
      recognition.onend = function () {
        startBtn.disabled = false;
        stopBtn.disabled = true;
        transcriptParagraph.textContent += ' (识别结束)';
      };

    } else {
      alert('您的浏览器不支持Web Speech API，请使用Chrome等支持的浏览器。');
    }
  </script>

</body>

</html>